package com.laicunba.service.accounting.impl;

import java.math.BigDecimal;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.laicunba.pojo.CashCouponDO;
import com.laicunba.pojo.CashCouponDefDO;
import com.laicunba.service.CashCouponDefService;
import com.laicunba.service.CashCouponService;
import com.laicunba.service.accounting.ActivityGrantCashCouponService;

@Service
public class ActivityGrantCashCouponServiceImpl implements ActivityGrantCashCouponService{
	private static final Logger LOG = Logger.getLogger(ActivityGrantCashCouponServiceImpl.class);
	@Autowired
	private CashCouponDefService cashCouponDefService;
	@Autowired
	private CashCouponService cashCouponService;

	@Transactional
	@SuppressWarnings("deprecation")
	public boolean grantCashCoupon(String userId, String cashCouponDefCode) {
		CashCouponDefDO defDO = cashCouponDefService.get(CashCouponDefDO.class, cashCouponDefCode);
		if (defDO == null) {
			LOG.error("活动(转盘)发放现金券红包出错:找不到现金券模版");
			return false;
		}

		CashCouponDO cashCouponDO = new CashCouponDO();
		cashCouponDO.setAmount(defDO.getAmount());
		cashCouponDO.setDefId(defDO.getId());
		cashCouponDO.setConditions(defDO.getConditions());
		cashCouponDO.setName(defDO.getName());
		cashCouponDO.setUsedAmount(BigDecimal.ZERO);
		cashCouponDO.setUserId(userId);
		cashCouponDO.setSummary("活动(转盘)自动派发现金券红包");
		if (defDO.getBeginTime() != null && defDO.getEndTime() != null) {
			cashCouponDO.setBeginTime(defDO.getBeginTime());
			cashCouponDO.setEndTime(defDO.getEndTime());
		}

		if (cashCouponDO.getEndTime() == null && defDO.getValidDay() > 0) {
			Date now = new Date();
			now.setHours(0);
			now.setMinutes(0);
			now.setSeconds(0);

			cashCouponDO.setBeginTime(new Date(now.getTime()));
			cashCouponDO.setEndTime(new Date(now.getTime()));
			cashCouponDO.getEndTime().setDate(cashCouponDO.getEndTime().getDate() + defDO.getValidDay());
		}

		if (cashCouponDO.getEndTime() == null || cashCouponDO.getBeginTime() == null) {
			return false;
		}
		return cashCouponService.create(cashCouponDO);

	}
}
